package com.sgy.springboot_demo.service;

import com.sgy.springboot_demo.mapper.EmployeeMapper;
import com.sgy.springboot_demo.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = {"emp"})
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*
     * @Cacheable：缓存查询，会将该方法的返回值存到缓存中
     * value/cacheNames：指定缓存名称
     * key：缓存数据时指定key值，默认是方法的参数值，也可以使用spel来计算key值
     * keyGenerator：key的生成策略，和key进行二选一
     * cacheManager：指定缓存管理器
     * cacheResolver：和cacheManager相同，二选一
     * condition：条件属性，满足这个条件才会缓存
     * unless：否定条件，满足这个条件不做缓存
     * sync：是否使用异步模式进行缓存
     * condition/unless同时满足，不缓存
     * sync的值为true时，unless不被支持
     * */
    @Cacheable(cacheNames = {"emp"}, key = "#id", condition = "#id > 0", unless = "#result == null")
    public Employee getEmpById(Integer id){
        return employeeMapper.getEmpById(id);
    }

    @CachePut(key = "#employee.id")
    public void updateEmp(Employee employee) {
        employeeMapper.updateEmp(employee);
    }

    @CacheEvict(key = "#id", beforeInvocation = true)
    public void delEmp(Integer id) {
        employeeMapper.deleteEmpById(id);
    }
}
